package thread;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池的使用；
 */
public class Demo11ThreadPool {
    public static void main(String[] args) {
        //需求：创建1个线程池，里边有2个线程，生成5个任务放到线程池中；
        /*
            1.创建线程池[2个线程]
            2.创建5个任务[Runnable]方式；
            3.创建1个将该任务提交到线程池中；
         */
        ExecutorService pool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 5; i++) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    Thread t = Thread.currentThread();
                    System.out.println(t + "正在执行任务");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(t + "执行任务结束");
                }
            };
            //提交任务
            pool.execute(r);
        }

        //关闭线程池
        //pool.shutdown()；
        pool.shutdownNow();
        System.out.println("线程池已关闭");
    }
}
